package com.xjwn.datasync.controller;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.xjwn.datasync.CommonResult;
import com.xjwn.datasync.pojo.DatasyncDb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/api")
public class DbtestContorller {

    /**
     * 测试数据库连接
     * @param datasyncdb datasync_db
     * @return true/false
     */
    @PostMapping("/DatabaseTest")
    public CommonResult<String> DatabaseTest(@RequestBody DatasyncDb datasyncdb) {
        // 参数非空校验
        if (datasyncdb == null || datasyncdb.getType() == null ||
                datasyncdb.getUrl() == null || datasyncdb.getUsername() == null ||
                datasyncdb.getPassword() == null) {
            return CommonResult.success("false");
        }

        String url="";
        String user = datasyncdb.getUsername();
        String password = datasyncdb.getPassword();
        String dbname = datasyncdb.getDbname();

        try {
            if ("Oracle".equalsIgnoreCase(datasyncdb.getType())) {
                url = "jdbc:oracle:thin:@//" + datasyncdb.getUrl();
            } else if ("SqlServer".equalsIgnoreCase(datasyncdb.getType())) {
                url = String.format("jdbc:sqlserver://%s;databaseName=%s;encrypt=false;trustServerCertificate=True;loginTimeout=120;",
                        datasyncdb.getUrl(), dbname);
            } else {
                log.info("不支持的数据库类型");
                return CommonResult.error(0,"不支持的数据库类型");
            }

            // 加载驱动（旧版本驱动需要，新版本可省略）
            Class.forName(datasyncdb.getType().equals("Oracle")
                    ? "oracle.jdbc.driver.OracleDriver"
                    : "com.microsoft.sqlserver.jdbc.SQLServerDriver");

            try (Connection scon = DriverManager.getConnection(url, user, password)) {
                scon.close();
                log.info("数据库测试连接成功");
                return CommonResult.success();
            }
        }
        catch (ClassNotFoundException e) {
            log.error("JDBC驱动未找到:url={};user={},password={},dbname={},错误信息:{}", url,user,password,dbname, e.getMessage());
            return CommonResult.error(0, e.getMessage());
        } catch (SQLException e) {
            log.error("数据库连接错误:url={};user={},password={},dbname={},错误信息:{}", url,user,password,dbname, e.getMessage());
            return CommonResult.error(0, e.getMessage());
        } catch (Exception e) {
            log.error("未知错误:url={};user={},password={},dbname={},错误信息:{}", url,user,password,dbname, e.getMessage());
            return CommonResult.error(0, e.getMessage());
        }
    }

    /**
     * 增加数据库连接信息
     * @param datasyncdb datasync_db
     * @return true/false
     */
    @PostMapping("/AddDatabase")
    public CommonResult<String> AddDatabase(@RequestBody DatasyncDb datasyncdb){
        try{
            boolean insert =  datasyncdb.insert();
            if(insert){
                return CommonResult.success();
            }else {
                log.info("插入数据库连接信息失败:url={};user={},password={},dbname={}", datasyncdb.getUrl(),datasyncdb.getUsername(),datasyncdb.getPassword(),datasyncdb.getDbname());
                return CommonResult.error(0,"插入数据库连接信息失败");
            }
        } catch (Exception e) {
            log.error("未知错误:url={};user={},password={},dbname={},错误信息:{}", datasyncdb.getUrl(),datasyncdb.getUsername(),datasyncdb.getPassword(),datasyncdb.getDbname(), e.getMessage());
//            System.err.println("未知错误: " + e.getMessage());
            return CommonResult.error(0,"未知错误");
        }
    }

    /**
     * 修改数据库连接信息
     *
     * @param datasyncdb datasync_db
     * @return true/false
     */
    @PostMapping("/UpdateDatabase")
    public CommonResult<String> UpdateDatabase(@RequestBody DatasyncDb datasyncdb) {
        try{
            DatasyncDb one = Db.lambdaQuery(DatasyncDb.class)
                    .eq(DatasyncDb::getName, datasyncdb.getName())
                    .one();

            boolean update = Db.saveOrUpdate(datasyncdb);
            if (update){
                return CommonResult.success();
            }
            else {
                log.info("修改连接信息时未找到数据库连接信息:url={};user={},password={},dbname={}", datasyncdb.getUrl(),datasyncdb.getUsername(),datasyncdb.getPassword(),datasyncdb.getDbname());
                return CommonResult.error(0,"修改连接信息时未找到数据库连接信息");
            }
        } catch (Exception e) {
            log.error("未知错误:url={};user={},password={},dbname={},错误信息:{}", datasyncdb.getUrl(),datasyncdb.getUsername(),datasyncdb.getPassword(),datasyncdb.getDbname(), e.getMessage());
            return CommonResult.error(0,"未知错误");
        }

    }

    /**
     * 删除数据库连接信息
     *
     * @param datasyncdb datasync_db
     * @return true/false
     */
    @PostMapping("/DelDatabase")
    public CommonResult<String> DelDatabase(@RequestBody DatasyncDb datasyncdb) {
        try{
            DatasyncDb one = Db.lambdaQuery(DatasyncDb.class)
                    .eq(DatasyncDb::getName, datasyncdb.getName())
                    .one();

            boolean del = Db.removeById(datasyncdb);
            if (del){
                return CommonResult.success();
            }
            else {
                log.info("删除连接信息时未找到数据库连接信息:url={};user={},password={},dbname={}", datasyncdb.getUrl(),datasyncdb.getUsername(),datasyncdb.getPassword(),datasyncdb.getDbname());
                return CommonResult.error(0,"删除连接信息时未找到数据库连接信息");
            }
        } catch (Exception e) {
            log.error("未知错误:url={};user={},password={},dbname={},错误信息:{}", datasyncdb.getUrl(),datasyncdb.getUsername(),datasyncdb.getPassword(),datasyncdb.getDbname(), e.getMessage());
            return CommonResult.error(0,"未知错误:"+e.getMessage());
        }
    }

    @PostMapping("/GetDblist")
    public CommonResult<List<DatasyncDb>> GetDblist(){
        return CommonResult.success(Db.lambdaQuery(DatasyncDb.class)
                .list());
    }
}
